package cn.lili.timetask.handler.impl.bill;

import cn.lili.common.enums.DictCodeEnum;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.DateUtil;
import cn.lili.common.utils.SysDictUtils;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.enums.FrozenEnum;
import cn.lili.modules.order.order.entity.enums.OrderStatusEnum;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.service.StoreService;
import cn.lili.modules.wallet.entity.dos.WalletLogDetail;
import cn.lili.modules.wallet.entity.dto.MemberWalletUpdateDTO;
import cn.lili.modules.wallet.entity.enums.DepositServiceTypeEnum;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.modules.wallet.service.MemberWalletService;
import cn.lili.timetask.handler.EveryDayExecute;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * StoreFrozenExecute. 商家冻结资金7天后解冻
 * 
 * @author Li Bing
 * @since 2022.03.26
 */
@Component
@Slf4j
public class StoreFrozenExecute implements EveryDayExecute {

	@Autowired
	private OrderService orderService;
	@Autowired
	private StoreService storeService;
	@Autowired
	private MemberWalletService memberWalletService;

	@Override
	public void execute() {
		// 查询7天前完成订单
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DAY_OF_YEAR,
				-Integer.getInteger(SysDictUtils.getValueString(DictCodeEnum.AUTO_RECEIVE.dictCode())));
		final Date time = calendar.getTime();
		LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Order::getOrderStatus, OrderStatusEnum.COMPLETED.name());
		queryWrapper.ge(Order::getCompleteTime, DateUtil.startOfTodDayTime(time));
		queryWrapper.le(Order::getCompleteTime, DateUtil.endOfDate(time));
		queryWrapper.eq(Order::getOwner, WalletOwnerEnum.SALE.name());
		queryWrapper.eq(Order::getFrozend, FrozenEnum.DONG_JIE.getCode());
		List<Order> list = orderService.list(queryWrapper);
		// 根据订单对商家进行遍历解冻资金
		if (!list.isEmpty()) {
			list.forEach(order -> {
				final Store store = storeService.getById(order.getStoreId());
				log.info("会员id:{}的店铺:{} 解冻资金 {} 元", store.getMemberId(), store.getStoreName(), order.getFlowPrice());
				try {
					unFrozen(store, order);
				} catch (Exception e) {
					log.error("会员id:{}的店铺:{} 解冻资金 {} 元，执行失败，订单id为：{}", store.getMemberId(), store.getStoreName(),
							order.getFlowPrice(), order.getId());
				}
			});
		}
	}

	@Transactional(rollbackFor = Exception.class)
	public void unFrozen(Store store, Order order) {
		// 修改订单标记
		final Boolean frozenStatusById = orderService.updateFrozenStatusById(order.getId(),
				FrozenEnum.DONG_JIE.getCode(), FrozenEnum.JIE_DONG.getCode());
		if (!frozenStatusById) {
			throw new ServiceException();
		}
		// 根据会员id，解冻资金
		// final Boolean aBoolean = memberWalletService
		// .updateFrozenWallet(store.getMemberId(),
		// order.getFlowPrice(),WalletOwnerEnum.STORE_SALE.name());

		final Boolean aBoolean = memberWalletService.increaseWithdrawal(new MemberWalletUpdateDTO(
				// order.getFlowPrice(),
				CurrencyUtil.sub(order.getFlowPrice(), order.getCommission()), store.getMemberId(),
				"订单[" + order.getSn() + "]解冻订单金额[" + order.getFlowPrice() + "]",
				DepositServiceTypeEnum.WALLET_PAY.name(), WalletOwnerEnum.SALE.name()),
				new WalletLogDetail(store.getStoreAddressPath(), store.getStoreAddressIdPath(), "3", order.getSn(),
						null, null, store.getMemberId(), store.getMemberName(), null, null, null,
						// order.getFlowPrice()
						CurrencyUtil.sub(order.getFlowPrice(), order.getCommission())));
		if (!aBoolean) {
			log.error("会员id:{}的店铺:{} 解冻资金 {} 元，执行失败，订单id为：{}", store.getMemberId(), store.getStoreName(),
					order.getFlowPrice(), order.getId());
		}

	}
}
